package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.CustomerMainOriginal;
import com.isunland.managesystem.entity.CustomerNeed;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.MyViewUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineView;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 客户需求详情页.
 *
 * @author wangyanan
 */
public class CustomerNeedFragment extends BaseFragment {
  public static final String EXTRA_TYPE = "com.isunland.managesystem.EXTRA_TYPE";
  public static final String CUSTOMER_ID = "com.isunland.managesystem.CUSTOMER_ID";
  public static final String CUSTOMERMAIN = "com.isunland.managesystem.CUSTOMERMAIN";
  public static final int VALUE_ADD = 1;
  public static final int VALUE_ALTER = 2;
  public static final int VALUE_SHOW = 0;
  protected static final String TAG = "CustomerNeedFragment";
  protected static final String EXTRA_CUSTOMER_NEED =
      "com.isunland.managesystem.EXTRA_CUSTOMER_NEED";
  private static final String FAILURE = "0";
  private static final String SUCCESS = "1";
  //private static final int REQUEST_lIST = 0;
  private static final int REQUEST_ALTER = 1;
  private static final int REQUEST_EXTRA_FILE_UPLOAD = 2;
  //private static final int REQUEST_EXTRA_FILE_DOWNLOAD = 3;
  private static final int REQUEST_CONTACTTIME = 4;
  private static final int REQUEST_SALENAME = 5;
  private static final int REQUEST_REGION = 6;
  private static final int REQUEST_INDUSTRY = 7;
  private static final int REQUEST_STAFF = 8;
  private static final int REQUEST_CUSTOMER = 9;
  private static final int REQUEST_NEED_PRODUCT = 10;
  /** 所在阶段 */
  private static final int REQUEST_STATE = 11;
  /** 信息来源 */
  private static final int REQUEST_INFO_SOURCE = 12;
  private static final int REQUEST_UPLOAD_SUCCESS = 13;

  private SingleLineView slvCustomerName;
  private SingleLineView slvRegion;
  private SingleLineView slvIndustry;
  private SingleLineView slvSalesMen;
  private RadioGroup rgCustomerType;
  private EditText etProduct;
  private TextView tvUnitStatus;
  private TextView tvInfoSource;
  private EditText etPhone;
  private EditText etDelegate;
  private EditText etMoney;
  private EditText etCommunicate;
  private TextView tvContactTime;
  private EditText etOtherDesc;
  private TextView tvSalesName;
  private TextView mTvExtraFile;

  private CustomerNeed mCustomerNeed;
  //private CustomerMainOriginal.rCustomerMain mCustomerDetail;
  private int mType;
  private CustomerMainOriginal.rCustomerMain mCustomerDetail;
  //private String mCustomerUnitStatusCode = "";
  //private String mCustomerInfoSource = "";
  //private String mSaleName = "";
  //private String mSaleCode = "";
  //private String mCustomerId = "";
  //private String mCustomerName = "";
  //private String mBelongDistrict = "";
  //private String mId = "";
  /**
   * 服务器回传的Android路径
   */
  //    private String mFileLocalPath = "";

  /**
   * 服务器回传的文件在服务器上的路径
   */
  //private String mFileServerPaht = "";
  //private String mFileName = "";

  //private String mDistrictCode;
  //private String mCustomerKindCode;
  //private String mJoinStaffCodes;

  //private RadioButton rbNewCustomer;
  //private RadioButton rbOldCustomer;
  public static CustomerNeedFragment newInstance(CustomerNeed customerNeed, int type,
      CustomerMainOriginal.rCustomerMain customerDetail) {
    Bundle argsBundle = new Bundle();
    argsBundle.putSerializable(EXTRA_CUSTOMER_NEED, customerNeed);
    argsBundle.putSerializable(EXTRA_TYPE, type);
    argsBundle.putSerializable(CUSTOMERMAIN, customerDetail);
    CustomerNeedFragment fragment = new CustomerNeedFragment();
    fragment.setArguments(argsBundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mCustomerNeed = (CustomerNeed) getArguments().getSerializable(EXTRA_CUSTOMER_NEED);
    mCustomerDetail =
        (CustomerMainOriginal.rCustomerMain) getArguments().getSerializable(CUSTOMERMAIN);
    mType = getArguments().getInt(EXTRA_TYPE);

    if (mCustomerNeed == null) mCustomerNeed = new CustomerNeed();
    if (mType == VALUE_ADD) {
      setTitleCustom(R.string.add_new_need);
      mCustomerNeed.setId(UUID.randomUUID().toString());
      mCustomerNeed.setSalesName(CurrentUser.newInstance(getActivity()).getRealName());
      mCustomerNeed.setSalesId(CurrentUser.newInstance(getActivity()).getJobNumber());
      //noinspection deprecation
      mCustomerNeed.setNearContactDate(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));
    } else if (mType == VALUE_ALTER) {
      setTitleCustom(R.string.alter_need);
    } else if (mType == VALUE_SHOW) {
      setTitleCustom(R.string.customer_need);
    } else {
      setTitleCustom(R.string.customer_need);
    }
    //mId = mCustomerNeed.getId();
    //mCustomerInfoSource = mCustomerNeed.getCustomerInfoFrom();
    //mCustomerUnitStatusCode = mCustomerNeed.getCustomerStatus();
    //mCustomerId = mCustomerNeed.getCustomerId();
    //mBelongDistrict = mCustomerNeed.getBelongDistrict();
    //mFileServerPaht = mCustomerNeed.getAppFileSavePaths();
    //mFileName = FileUtil.getFileNameByFilePath(mFileServerPaht);
    //mSaleName = mCustomerNeed.getSalesName();
    //mSaleCode = mCustomerNeed.getSalesId();
    //mDistrictCode = mCustomerNeed.getDistrictCode();
    ////String mDistrictDesc = mCustomerNeed.getDistrictDesc();
    //mCustomerKindCode = mCustomerNeed.getCustomerKindCode();
    //mJoinStaffCodes = mCustomerNeed.getJoinStaffCodes();
    if (mCustomerDetail != null) {
      mCustomerNeed.setCustomerId(mCustomerDetail.getId());
      mCustomerNeed.setCustomerName(mCustomerDetail.getCustomerName());
      mCustomerNeed.setBelongDistrict(mCustomerDetail.getDistrictDesc());
      mCustomerNeed.setNearCustomerName(mCustomerDetail.getContactManNames());
      mCustomerNeed.setNearCustomerPhone(mCustomerDetail.getContactNum());
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_customer_need, container, false);
    findViews(v);

    return v;
  }

  private void findViews(View v) {

    slvCustomerName = (SingleLineView) v.findViewById(R.id.slv_customerName);
    etProduct = (EditText) v.findViewById(R.id.et_product_customerNeed);
    tvUnitStatus = (TextView) v.findViewById(R.id.tv_unitStatus_customerNeed);
    tvInfoSource = (TextView) v.findViewById(R.id.tv_infoSource_customerNeed);
    mTvExtraFile = (TextView) v.findViewById(R.id.tv_extraFile_customerNeed);
    ImageView mIvExtraFile = (ImageView) v.findViewById(R.id.iv_extraFile);
    etPhone = (EditText) v.findViewById(R.id.et_phone_customerNeed);
    etDelegate = (EditText) v.findViewById(R.id.et_delegate_customerNeed);
    etMoney = (EditText) v.findViewById(R.id.et_money_customerNeed);
    etCommunicate = (EditText) v.findViewById(R.id.et_communicate_customerNeed);

    tvSalesName = (TextView) v.findViewById(R.id.tv_salesName);
    tvContactTime = (TextView) v.findViewById(R.id.tv_contactTime);
    etOtherDesc = (EditText) v.findViewById(R.id.et_otherDesc);
    slvRegion = (SingleLineView) v.findViewById(R.id.slv_region);
    slvIndustry = (SingleLineView) v.findViewById(R.id.slv_industry);
    slvSalesMen = (SingleLineView) v.findViewById(R.id.slv_salesMen);
    rgCustomerType = (RadioGroup) v.findViewById(R.id.rg_customerType);
    slvSalesMen.getTvContent().setText(mCustomerNeed.getJoinStaffNames());
    slvCustomerName.getTvContent().setText(mCustomerNeed.getCustomerName());
    tvSalesName.setText(mCustomerNeed.getSalesName());
    etDelegate.setText(mCustomerNeed.getNearCustomerName());
    tvContactTime.setText(mCustomerNeed.getNearContactDate());
    etProduct.setText(mCustomerNeed.getNeedProductDesc());
    tvUnitStatus.setText(mCustomerNeed.getCustomerStatusText());
    tvInfoSource.setText(mCustomerNeed.getCustomerInfoFromText());
    etPhone.setText(mCustomerNeed.getNearCustomerPhone());
    etMoney.setText(mCustomerNeed.getFundEstimate());
    etCommunicate.setText(mCustomerNeed.getNearCommDesc());
    mTvExtraFile.setText(FileUtil.getFileNameByFilePath(mCustomerNeed.getAppFileSavePaths()));
    etOtherDesc.setText(mCustomerNeed.getRemark());

    MyViewUtil.setParams(etDelegate, "nearCustomerName");
    MyViewUtil.setParams(tvUnitStatus, "customerStatusText");
    MyViewUtil.setParams(tvInfoSource, "customerInfoFromText");
    MyViewUtil.setParams(etProduct, "needProductDesc");
    MyViewUtil.setParams(etCommunicate, "nearCommDesc");
    MyViewUtil.setParams(tvSalesName, "salesName");
    MyViewUtil.setParams(etPhone, "nearCustomerPhone");
    MyViewUtil.setParams(etMoney, "fundEstimate");
    MyViewUtil.setParams(tvContactTime, "nearContactDate");
    MyViewUtil.setParams(etOtherDesc, "remark");
    MyViewUtil.setParams(slvRegion.getTvContent(), "districtDesc");
    MyViewUtil.setParams(slvSalesMen.getTvContent(), "joinStaffNames");
    MyViewUtil.setParams(slvCustomerName.getTvContent(), "customerName");

    etProduct.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(
            CustomerDialogFragment.newInstance(CustomerDialogFragment.VALUE_TYPE_CUSTOMER_PRODUCT),
            REQUEST_NEED_PRODUCT);
      }
    });
    tvUnitStatus.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(CustomerDialogFragment.newInstance(
            CustomerDialogFragment.VALUE_TYPE_CUSTOMER_UNIT_STATE), REQUEST_STATE);
      }
    });
    tvInfoSource.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(CustomerDialogFragment.newInstance(
            CustomerDialogFragment.VALUE_TYPE_CUSTOMER_INFO_SOURCE), REQUEST_INFO_SOURCE);
      }
    });
    mTvExtraFile.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        downFile(mCustomerNeed.getAppFileSavePaths());
      }
    });
    mIvExtraFile.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        chooseFile(REQUEST_EXTRA_FILE_UPLOAD);
      }
    });
    tvSalesName.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        Intent i = new Intent(getActivity(), SearchPersonActivity.class);
        i.putExtra(SearchPersonListFragment.EXTRA_FROM, SearchPersonListFragment.VALUE_COMMON);
        startActivityForResult(i, REQUEST_SALENAME);
      }
    });
    tvContactTime.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(new BaseYMDTimeDialogFragment(), REQUEST_CONTACTTIME);
      }
    });
    slvRegion.getTvContent().setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(new DistrictDialogFragment(), REQUEST_REGION);
      }
    });
    slvIndustry.getTvContent().setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(new UnitTypeDialogFragment(), REQUEST_INDUSTRY);
      }
    });
    slvSalesMen.getTvContent().setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        Intent staffIntent = new Intent(getActivity(), SearchPersonMultipleActicity.class);
        staffIntent.putExtra(SearchPersonMultipleFragment.EXTRA_FROM,
            SearchPersonMultipleFragment.VALUE_COMMON);
        staffIntent.putExtra(SearchPersonMultipleFragment.EXTRA_JOB, "");
        startActivityForResult(staffIntent, REQUEST_STAFF);
      }
    });
    slvCustomerName.getTvContent().setOnClickListener(new CustomerNameClickLisener());
    rgCustomerType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(RadioGroup group, int checkedId) {
        //选择新客户,显示行业和区域选择
        if (checkedId == R.id.rb_newCustomer) {
          slvIndustry.setVisibility(View.VISIBLE);
          slvRegion.setVisibility(View.VISIBLE);
          slvCustomerName.setType(SingleLineView.NORMAL);
          slvCustomerName.setHint(getString(R.string.inputMust));
          slvCustomerName.setOnClickContentListener(null);
        }
        //选择旧客户,禁用行业和区域选择
        if (checkedId == R.id.rb_oldCustomer) {
          slvIndustry.setVisibility(View.GONE);
          slvRegion.setVisibility(View.GONE);
          slvCustomerName.setType(SingleLineView.NEXT);
          slvCustomerName.setHint(getString(R.string.chooseMust));
          slvCustomerName.setOnClickContentListener(new CustomerNameClickLisener());
        }
      }
    });

    //只有新增客户需求(不是来自于客户名录)的时候可以选新老客户,可以选客户
    if (!(VALUE_ADD == mType && mCustomerDetail == null)) {
      rgCustomerType.setVisibility(View.GONE);
      slvCustomerName.getTvContent().setEnabled(false);
    }

    //详情的时候禁用选择框
    if (mType == VALUE_SHOW) {
      MyViewUtil.setEnableAll(false, slvSalesMen.getTvContent(), slvRegion.getTvContent(),
          slvIndustry.getTvContent(), etProduct, etPhone, etDelegate, etMoney, tvInfoSource,
          tvUnitStatus, tvContactTime, tvSalesName, etCommunicate, etOtherDesc, mIvExtraFile);
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate((mType == VALUE_ADD || mType == VALUE_ALTER) ? R.menu.menu_confirm
        : R.menu.menu_alter_delete, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.menu_item_confirm) {
      saveCustomerNeed();
      return true;
    }
    if (item.getItemId() == R.id.menu_item_alter) {
      if (!mCurrentUser.getJobNumber().equals(mCustomerNeed.getRegStaffId())) {
        Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
        return false;
      }
      //只能修改24小时以内的记录.
      //只能删除24以内的记录.
      Intent i = new Intent(getActivity(), CustomerNeedActivity.class);
      i.putExtra(CustomerNeedFragment.EXTRA_CUSTOMER_NEED, mCustomerNeed);
      i.putExtra(CustomerNeedFragment.EXTRA_TYPE, CustomerNeedFragment.VALUE_ALTER);
      startActivityForResult(i, REQUEST_ALTER);
      return true;
    }
    if (item.getItemId() == R.id.menu_item_delete) {

      deleteCustomerNeed();
      return true;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_NEED_PRODUCT && data != null) {
      CustomerDialog customerDialog =
          (CustomerDialog) data.getSerializableExtra(CustomerDialogFragment.EXTRA_VALUE);
      mCustomerNeed.setNeedProductDesc(customerDialog.getName());
      etProduct.setText(customerDialog.getName());
    }
    if (requestCode == REQUEST_STATE && data != null) {
      CustomerDialog customerDialog =
          (CustomerDialog) data.getSerializableExtra(CustomerDialogFragment.EXTRA_VALUE);
      mCustomerNeed.setCustomerStatus(customerDialog.getId());
      mCustomerNeed.setCustomerStatusText(customerDialog.getName());
      tvUnitStatus.setText(customerDialog.getName());
    }
    if (requestCode == REQUEST_INFO_SOURCE && data != null) {
      CustomerDialog customerDialog =
          (CustomerDialog) data.getSerializableExtra(CustomerDialogFragment.EXTRA_VALUE);
      mCustomerNeed.setCustomerInfoFrom(customerDialog.getId());
      mCustomerNeed.setCustomerInfoFromText(customerDialog.getName());
      tvInfoSource.setText(customerDialog.getName());
    }

    if (requestCode == REQUEST_ALTER) {
      mActivity.setResult(Activity.RESULT_OK);
      mActivity.finish();
    }
    if (requestCode == REQUEST_EXTRA_FILE_UPLOAD) {

      showDialog(FileUploadDialgFragment.newInstance(getFile(data), mCustomerNeed.getId(),
          "r_customerneed_list_main", false), REQUEST_UPLOAD_SUCCESS);
    }
    if (requestCode == REQUEST_UPLOAD_SUCCESS) {
      String filepath = data.getStringExtra(FileUploadDialgFragment.EXTRA_PATH);
      mTvExtraFile.setText(FileUtil.getFileNameByFilePath(filepath));
      mCustomerNeed.setAppFileSavePaths(filepath);
    }
    if (requestCode == REQUEST_CONTACTTIME) {
      //往来时间
      Date acquireDate = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      //@SuppressWarnings("deprecation") String time =
      //    MyDateUtil.dateToString(acquireDate, MyDateUtil.TYPE_DATE);
      mCustomerNeed.setNearContactDate(MyDateUtil.format(acquireDate, MyDateUtil.TYPE_DATE));
      tvContactTime.setText(MyDateUtil.format(acquireDate, MyDateUtil.TYPE_DATE));
    }
    if (requestCode == REQUEST_SALENAME) {
      //销售代表
      CustomerDialog dialog =
          (CustomerDialog) data.getSerializableExtra(SearchPersonListFragment.EXTRA_VALUE);
      if (dialog == null) return;
      mCustomerNeed.setSalesName(dialog.getName());
      mCustomerNeed.setSalesId(dialog.getJobNo());
      tvSalesName.setText(dialog.getName());
    }
    if (requestCode == REQUEST_CUSTOMER && data != null) {
      //slvCustomerName.getTvContent().setText(data.getStringExtra("customerName"));
      //mCustomerId = data.getStringExtra("customerId");
      //甲方客户
      CustomerMainOriginal.rCustomerMain customer = data.getSerializableExtra(
          CustomerListChooseFragment.EXTRA_CONTENT) instanceof CustomerMainOriginal.rCustomerMain
          ? (CustomerMainOriginal.rCustomerMain) data.getSerializableExtra(
          CustomerListChooseFragment.EXTRA_CONTENT)
          : new CustomerMainOriginal().new rCustomerMain();
      mCustomerNeed.setCustomerId(customer.getId());
      mCustomerNeed.setCustomerName(customer.getCustomerName());
      mCustomerNeed.setBelongDistrict(customer.getDistrictDesc());
      mCustomerNeed.setNearCustomerName(customer.getContactManNames());
      mCustomerNeed.setNearCustomerPhone(customer.getContactNum());

      slvCustomerName.getTvContent().setText(customer.getCustomerName());
      etDelegate.setText(customer.getContactManNames());
      etPhone.setText(customer.getContactNum());
    }
    if (requestCode == REQUEST_INDUSTRY) {
      CustomerDialog customerDialog =
          (CustomerDialog) data.getSerializableExtra(UnitTypeDialogFragment.EXTRA_VALUE);
      mCustomerNeed.setCustomerKindCode(customerDialog.getId());
      slvIndustry.getTvContent().setText(customerDialog.getName());
    }
    if (requestCode == REQUEST_REGION) {
      CustomerDialog customerDialog =
          (CustomerDialog) data.getSerializableExtra(DistrictDialogFragment.EXTRA_VALUE);
      mCustomerNeed.setDistrictDesc(customerDialog.getName());
      mCustomerNeed.setDistrictCode(customerDialog.getId());
      slvRegion.getTvContent().setText(customerDialog.getName());
    }
    if (requestCode == REQUEST_STAFF) {
      String names = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_NAME);
      String jobNos = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_JOB);
      mCustomerNeed.setJoinStaffNames(names);
      mCustomerNeed.setJoinStaffCodes(jobNos);
      slvSalesMen.setTextContent(names);
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  private void deleteCustomerNeed() {
    if (!mCurrentUser.getJobNumber().equals(mCustomerNeed.getRegStaffId())) {
      Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
      return;
    }
    if (!MyUtils.isNetLink(getActivity())) {
      Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_SHORT).show();
      return;
    }
    new AlertDialog.Builder(mActivity).setMessage(R.string.deleteConfirm)
        .setNegativeButton(android.R.string.cancel, null)
        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialog, int which) {
            volleyPostDeleteCustomerNeed();
          }
        })
        .show();
  }

  private void volleyPostDeleteCustomerNeed() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE_CUSTOMER_NEED);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mCustomerNeed.getId());

    LogUtil.i(TAG, "url=" + ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE_CUSTOMER_NEED));
    LogUtil.i(TAG, "params=" + params.toString());

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          LogUtil.i(TAG, "response=" + arg0);
          SuccessMessage custoomerMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == custoomerMessage || null == custoomerMessage.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = custoomerMessage.getResult();
          if (successType.equals(FAILURE)) {
            ToastUtil.show(custoomerMessage.getMessage(), getString(R.string.failure_operation));
            return;
          }
          if (successType.equals(SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            //                        new FileNetWorkUtil(getActivity()).upLoadFile(mFileLocalPath, ApiConst.URL_UPLOAD_FILE,
            //                                "r_customerneed_list_main", custoomerMessage.getMessage(), null);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          LogUtil.e(TAG, "error=" + e, e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  private void saveCustomerNeed() {
    if (!MyUtils.isNetLink(getActivity())) {
      Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_SHORT).show();
      return;
    }
    if (MyViewUtil.isEmptyText(slvCustomerName.getTvContent(), etProduct, tvUnitStatus,
        tvInfoSource, etMoney, tvSalesName, tvContactTime, etPhone, etDelegate)) {
      Toast.makeText(getActivity(), R.string.incomplete_message, Toast.LENGTH_SHORT).show();
      return;
    }

    volleyPostAddCustomerNeed();
  }

  private void volleyPostAddCustomerNeed() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ADD_CUSTOMER_NEED_V290);
    ParamsNotEmpty params = new ParamsNotEmpty();
    //如果客户id为空,本地生成客户id.
    String customerId =
        MyStringUtil.isEmpty(mCustomerNeed.getCustomerId()) ? UUID.randomUUID().toString()
            : mCustomerNeed.getCustomerId();
    mCustomerNeed.setCustomerId(customerId);
    params.putAll(mCustomerNeed, etDelegate, tvUnitStatus, tvInfoSource, etProduct, etCommunicate,
        tvSalesName, etPhone, etMoney, tvContactTime, etOtherDesc, slvRegion.getTvContent(),
        slvSalesMen.getTvContent(), slvCustomerName.getTvContent());

    params.put("isNew ",
        String.valueOf(rgCustomerType.getCheckedRadioButtonId() == R.id.rb_newCustomer));

    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          LogUtil.i(TAG, "response=" + arg0);
          SuccessMessage custoomerMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == custoomerMessage || null == custoomerMessage.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = custoomerMessage.getResult();
          if (successType.equals(FAILURE)) {
            ToastUtil.show(custoomerMessage.getMessage(), getString(R.string.failure_operation));
            return;
          }
          if (successType.equals(SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          LogUtil.e(TAG, "error=" + e, e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  private void chooseFile(int requestCode) {
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        requestCode);
  }

  private String getFile(Intent data) {
    String path1 = FileUtil.getPath(getActivity(), data.getData());
    File mFile = null;
    if (path1 != null) {
      mFile = new File(path1);
    }
    if (null == mFile) {
      Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      return "";
    }
    return mFile.getAbsolutePath();
  }

  private void downFile(String serverPath) {
    if (!TextUtils.isEmpty(serverPath)) {
      showDialog(ExtraDownLoadDialogFragment.newInstance("", serverPath), 0);
    }
  }

  //private void volleyPostExtra(String resourcefilePath) {
  //
  //  if (!TextUtils.isEmpty(resourcefilePath)) {
  //    new FileNetWorkUtil(getActivity()).upLoadFile(resourcefilePath, ApiConst.URL_UPLOAD_FILE,
  //        "r_customerneed_list_main ", mCustomerNeed.getId(), new myUpLoadHandler(), false);
  //  }
  //}

  //private class myUpLoadHandler extends AsyncHttpResponseHandler {
  //
  //  public myUpLoadHandler() {
  //  }
  //
  //  @Override public void onStart() {
  //    MyUtils.showDialogLoading(getActivity());
  //    super.onStart();
  //  }
  //
  //  @SuppressWarnings("deprecation") @Override
  //  public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
  //    MyUtils.dismissDialog();
  //    ToastUtil.show(R.string.fileUploadFailure);
  //  }
  //
  //  @Override
  //  public void onSuccess(int arg0, @SuppressWarnings("deprecation") Header[] arg1, byte[] arg2)
  //      throws Resources.NotFoundException {
  //    MyUtils.dismissDialog();
  //    LogUtil.i("arg2==" + new String(arg2));
  //    try {
  //
  //      SuccessMessage result = new Gson().fromJson(new String(arg2), SuccessMessage.class);
  //      if (result == null) {
  //        MyUtils.dismissDialog();
  //        ToastUtil.show(R.string.wrong_data);
  //      }
  //      if (result != null && result.getResult() != null && result.getResult().equals("1")) {
  //        // 上传成功,再上传数据
  //        ToastUtil.show(R.string.fileUploadSuccess);
  //        String selcurFile = result.getMessage();
  //        mTvExtraFile.setText(FileUtil.getFileNameByFilePath(selcurFile));
  //        mCustomerNeed.setAppFileSavePaths(selcurFile);
  //      } else {
  //        MyUtils.dismissDialog();
  //        ToastUtil.show(result != null ? result.getMessage() : "");
  //      }
  //    } catch (JsonSyntaxException e) {
  //      e.printStackTrace();
  //      ToastUtil.show(R.string.fileUploadFailure);
  //    }
  //  }
  //}

  private class CustomerNameClickLisener implements OnClickListener {

    @Override public void onClick(View v) {
      Intent customer = new Intent(getActivity(), CustomerListChooseActivity.class);
      startActivityForResult(customer, REQUEST_CUSTOMER);
    }
  }
}
